<template>
  <div class="config_container">
    <!-- 配置表单区域 -->
    <div class="config_section">
      <h2 class="section_title">点击设置</h2>
      <el-divider></el-divider>

      <!-- 鼠标按键选择 -->
      <div class="config_line">
        <div class="label">鼠标按键：</div>
        <el-select
          v-model="config.clickButton"
          class="config_input"
          placeholder="请选择鼠标按键"
          @change="updateConfig"
        >
          <el-option value="left" label="鼠标左键" />
          <el-option value="right" label="鼠标右键" />
          <el-option value="middle" label="鼠标中键" />
        </el-select>
      </div>

      <!-- 点击次数 -->
      <div class="config_line">
        <div class="label">点击次数：</div>
        <el-select
          v-model="config.clickCount"
          class="config_input"
          placeholder="请选择鼠标按键"
          @change="updateConfig"
        >
          <el-option value="single" label="单击" />
          <el-option value="double" label="双击" />
        </el-select>
      </div>

      <!-- 位置设置 -->
      <div class="config_line position_config">
        <div class="label">位置设置：</div>
        <!-- 位置模式选择 -->
        <el-select v-model="config.position.type" class="config_input" @change="updateConfig">
          <el-option label="当前鼠标位置" value="cursor" />
          <el-option label="指定坐标位置" value="manual" />
        </el-select>
      </div>
      <!-- 手动坐标输入 -->
      <div class="config_line" v-show="config.position.type === 'manual'">
        <div class="label">点击坐标：</div>
        <!-- 手动坐标输入 -->
        <div class="position_inputs">
          <label>X:</label>
          <el-input-number
            v-model="config.position.x"
            :min="0"
            :max="screenWidth"
            placeholder="X"
            controls-position="right"
            class="pos_input"
            @change="updateConfig"
          />
          <label>Y:</label>
          <el-input-number
            v-model="config.position.y"
            :min="0"
            :max="screenHeight"
            placeholder="Y"
            controls-position="right"
            class="pos_input"
            @change="updateConfig"
          />
          <el-button @click="handleGetPostion">选取坐标</el-button>
        </div>
      </div>
      <!-- 持续时间 -->
      <div class="config_line">
        <span class="label">持续时间(ms)：</span>
        <time-input v-model="config.clickDuration" @update="updateConfig"></time-input>
      </div>

      <!-- 间隔时间 -->
      <interval-time v-model="config.interval" :min="10" @update="updateConfig" />
      <!-- 停止条件设置 -->
      <stop-condition v-model="config.stop" @update="updateConfig('stop')" />
    </div>
    <!-- 操作按钮 -->
    <div class="action_container">
      <el-button
        @keydown.space.prevent
        @keydown.enter.prevent
        class="action_button"
        :type="isRunning ? 'danger' : 'primary'"
        :icon="isRunning ? VideoPause : VideoPlay"
        @click="toggleExecutor"
      >
        {{ isRunning ? '紧急停止' : '开始运行' }}({{ hotkeyLabel }})
      </el-button>
    </div>
    <!-- 状态显示 -->
    <div class="status_box">
      <el-alert :title="message" type="info" :closable="false" />
    </div>
  </div>
</template>
<script setup>
import { VideoPlay, VideoPause } from '@element-plus/icons-vue'
import { inject, ref, onMounted, onUnmounted } from 'vue'
import { ElMessage } from 'element-plus'
import request from '@/utils/request.js'
import StopCondition from '@/components/stopCondition.vue'
import intervalTime from '@/components/intervalTime.vue'
import timeInput from '@/components/timeInput.vue'

// 组件会自动在模板中可用，直接使用 <video-play>
const config = ref({
  clickButton: 'left',
  clickCount: 'single',
  position: {
    // 注意: 原代码拼写错误 postion 已修正为 position
    type: 'cursor', // cursor / manual
    x: 0,
    y: 0,
  },
  stop: {
    type: 'FOREVER',
    maxTime: 0,
    maxExecutions: 0,
  },
  clickDuration: 100,
  interval: 100,
  channel: '/topic/mouse-executor',
})

// 假设这两个值来自其他逻辑，这里用示例值
const screenWidth = ref(window.screen.width)
const screenHeight = ref(window.screen.height)
const isRunning = ref(false)
const message = ref('执行器暂未启动')

// 修改 updateConfig 方法
const updateConfig = async (from) => {
  console.log('前端更新配置到后端, 更新来源：', from)
  const res = await request.postJson('/mouse/config', config.value)
  if (res.code == 0) {
    config.value = res.data.config // 确保后端返回最新配置
  }
}

function handleGetPostion() {
  request.post('/mouse/listener/mouse')
}

function toggleExecutor() {
  if (!validateConfig()) return
  request.post('/mouse/toggle')
}

function validateConfig() {
  if (config.value.position.type === 'manual') {
    if (!config.value.position.x || !config.value.position.y) {
      ElMessage.warning('请填写坐标位置')
      return false
    }
    if (
      config.value.position.x > screenWidth.value ||
      config.value.position.y > screenHeight.value
    ) {
      ElMessage.warning('坐标超出屏幕范围')
      return false
    }
  }
  return true
}
onMounted(updateConfig)
const hotkeyLabel = ref('F9')
onMounted(async () => {
  const res = await request.get(`/setting/name/mouse.toggle`)
  hotkeyLabel.value = res.data.key
})

// 获取全局实例（两种方式可选）
const webSocketManager = inject('webSocketManager') // 推荐通过inject获取
// 页面级订阅逻辑
const handleExecutorStatus = (status) => {
  isRunning.value = status.state === 'RUNNING' || status.state === 'COUNTDOWN'
  message.value = status.messages[status.messages.length - 1].message
}

const handleMouseMove = (status) => {
  config.value.position.x = status.x
  config.value.position.y = status.y
}

// 订阅消息
onMounted(() => {
  webSocketManager.subscribe('/topic/mouse-executor', handleExecutorStatus)
  webSocketManager.subscribe('/topic/mouse-move', handleMouseMove)
  request.post('/mouse/bind')
  webSocketManager.setConnectCallback(() => {
    updateConfig('connect')
  })
})

// 取消订阅
onUnmounted(() => {
  webSocketManager.unsubscribe('/topic/mouse-executor')
  webSocketManager.unsubscribe('/topic/mouse-move')
  request.post('/mouse/unbind')
})
</script>

<style lang="less" scoped>
@import url('../assets/main.less');

.config_container {
  padding: 0px 24px;
  border-radius: 12px;

  .section_title {
    color: var(--el-text-color-primary);
    font-size: 1.5em;
    margin-bottom: 1em;
    position: relative;
    margin-top: 10px;

    &::after {
      content: '';
      position: absolute;
      bottom: -8px;
      left: 0;
      width: 50px;
      height: 3px;
      background: @primary-color;
    }
  }

  .config_line {
    .config-line();

    .position_inputs {
      display: flex;
      align-items: center;
      flex-wrap: wrap;
      gap: 10px;

      .pos_input {
        width: 120px;
        transition: all 0.3s;

        &:hover {
          border-color: @primary-color;
        }
      }
    }
  }

  .action_container {
    width: 100%;
    display: flex;

    .action_button {
      margin: auto;
      width: 60%;
      padding: 12px 32px;
      border-radius: 6px;
      font-weight: 600;
      transition: all 0.3s;

      &:hover {
        transform: translateY(-2px);
        box-shadow: 0 4px 12px rgba(@primary-color, 0.3);
      }
    }
  }

  .status_box {
    margin-top: 24px;

    .el-alert {
      border-radius: 6px;
      background: rgba(#909399, 0.08);
      border: 1px solid #ebeef5;
    }
  }
}
</style>
